package box.interview.wx.miniapp.service.impl;

import box.interview.wx.miniapp.config.ApplicationConfig;
import box.interview.wx.miniapp.entity.WxMiniappInterview;
import box.interview.wx.miniapp.mapper.WxMiniappInterviewMapper;
import box.interview.wx.miniapp.service.ICollectRankingService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class CollectRankingServiceImpl implements ICollectRankingService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ApplicationConfig applicationConfig;

    @Autowired
    private WxMiniappInterviewMapper wxMiniappInterviewMapper;


    @Override
    public List<WxMiniappInterview> getDataCollectRanking(Integer size) {
        String collect2ranking = applicationConfig.collect2ranking;
        // 从大到小查询
        List<Long> interviewIdList = new ArrayList<>();
        Set<ZSetOperations.TypedTuple<String>> set = redisTemplate.opsForZSet().reverseRangeByScoreWithScores(collect2ranking, 0, Integer.MAX_VALUE, 0, size);
        for (ZSetOperations.TypedTuple<String> item : set) {
            String value = item.getValue();
            if (value != null && value.length() > 0) {
                String interviewIdStr = value.split("-")[1];
                Long interviewId = Long.valueOf(interviewIdStr);
                interviewIdList.add(interviewId);
            }
        }
        if (interviewIdList.size() == 0) {
            return new ArrayList<>();
        }
        QueryWrapper<WxMiniappInterview> wrapper = new QueryWrapper<>();
        wrapper.in("id", interviewIdList);
        List<WxMiniappInterview> list = wxMiniappInterviewMapper.selectList(wrapper);
        return list;
    }
}
